package zut.wework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import zut.wework.api.WxApi;
import zut.wework.entity.*;
import zut.wework.init.InitializationDept;
import zut.wework.mapper.BzksBjMapper;
import zut.wework.mapper.BzksYxMapper;
import zut.wework.mapper.BzksZyMapper;
import zut.wework.mapper.WxDeptMapper;
import zut.wework.service.IWxDeptService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 刘铭心
 * @since 2022-03-22
 */
@Slf4j
@Service
public class WxDeptServiceImpl implements IWxDeptService {

    @Autowired
    private InitializationDept dept;

    @Autowired
    private WxDeptMapper wxDeptMapper;

    @Autowired
    private WxApi wxApi;

    @Autowired
    private BzksZyMapper bzksZyMapper;
    @Autowired
    private BzksBjMapper bzksBjMapper;
    @Autowired
    private BzksYxMapper bzksYxMapper;

    private static final ReentrantLock wxLock = new ReentrantLock();

    @Override
    public Result syncWx() {

        wxLock.lock();
        try {
            Map<Integer, WxDept> tempDepts = new HashMap<>();
            new Thread(() -> {
                log.info("{}:开始同步", Thread.currentThread().getName());
                List<WxDept> wxDepts = wxDeptMapper.selectAll();
                HashMap<String, WxDept> wxDeptHashMap = new HashMap<>();
                wxDepts.forEach(i -> wxDeptHashMap.put(i.getType_id() + i.getParentid(), i));
                if (wxDeptHashMap.size() == 0) {//首次同步
                    int b = wxDeptMapper.insert(new WxDept(1, "花瓣舞者", null, 0, 1000, "1", "0"));
                    tempDepts.put(1, new WxDept(1, "花瓣舞者", null, 0, 1000, "1", "0"));
                    wxApi.creatDept(new WxDept(null, "本专科生", null, 1, 1000, "2", "0"));
                    tempDepts.put(2, new WxDept(2, "本专科生", null, 1, 1000, "2", "0"));
                    int years = dept.allMap.keySet().size();//获得年级数量
                    for (int i = 0, y = dept.year; i < years; i++, y--) {
                        WxDept dept = new WxDept(null, y + "级", null, 1, 1000 + i, i + 3 + "", "0");
                        if (wxApi.creatDept(dept)) {
                            log.info("{}:添加部门：{}成功", Thread.currentThread().getName(), y + "级");
                        } else {
                            log.error("{}:添加失败", Thread.currentThread().getName());
                        }
                        tempDepts.put(i + 3, new WxDept(i + 3, y + "级", null, 1, 1000 + i, i + 3 + "", "0"));
                    }
                }
                if (tempDepts.size() == 0) {
                    tempDepts.put(1, new WxDept(1, "花瓣舞者", null, 0, 1000, "1", "0"));
                    tempDepts.put(2, new WxDept(2, "本专科生", null, 1, 1000, "2", "0"));
                    int years = dept.allMap.keySet().size();//获得年级数量
                    for (int i = 0, y = dept.year; i < years; i++, y--) {
                        tempDepts.put(i + 3, new WxDept(i + 3, y + "级", null, 1, 1000 + i, i + 3 + "", "0"));
                    }
                }
                //不是首次同步
                //同步院系和专业
                for (Integer year : dept.allMap.keySet()) {
                    WxDept nj = wxDeptMapper.selectDept(new WxDept(null, year + "级", null, null, null, null, null));
                    if (nj != null) {
                        tempDepts.put(nj.getId(), nj);
                    }
                    for (BzksYx yx : dept.allMap.get(year)) {//根据年级获得院系
                        assert nj != null;
                        WxDept yuanxi = new WxDept(null, yx.getMc(), null, nj.getId(), nj.getPx(), yx.getDm(), "1");
                        //是否更新院系
    //                    log.info("{}院系key:{}{}", yx.getMc(), yx.getDm() + nj.getId(), wxDeptHashMap.get(yx.getDm() + nj.getId()));
                        WxDept yxDept = wxDeptMapper.selectDept(new WxDept(null, null, null, null, nj.getPx(), yx.getDm(), "1"));
    //                    log.info("{}院系: {}", yxDept.getName(), yxDept);
    //                    if (wxDeptHashMap.containsKey(yx.getDm() + nj.getId())) {//更新名称
    //                        WxDept wxDept1 = wxDeptMapper.selectDept(new WxDept(null, null, null, nj.getId(), null, yx.getDm(), null));
                        if (yxDept != null) {
                            yuanxi.setId(yxDept.getId());
                            if (!yuanxi.equals(yxDept)) {

                                wxApi.updateDept(yuanxi);
                            }
                        } else {
                            if (wxApi.creatDept(yuanxi)) {
                                log.info("{}:添加院系部门：{}成功", Thread.currentThread().getName(), yx.getMc());
                            } else {
                                log.error("{}:添加院系失败", yx.getMc());
                            }
                        }

                        //专业数据
                        List<BzksZy> zyList = bzksZyMapper.selectZyById(yx.getDm(), dept.year - year);
                        WxDept yxInfo = wxDeptMapper.selectDept(new WxDept(null, yx.getMc(), null, nj.getId(), null, null, null));
                        if (yxInfo != null) {
                            tempDepts.put(yxInfo.getId(), yxInfo);
                        }
                        for (BzksZy bzksZy : zyList) {
                            assert yxInfo != null;
                            WxDept dept = new WxDept(null, bzksZy.getMc(), null, yxInfo.getId(), yxInfo.getPx(), bzksZy.getDm(), "2");
                            log.info("{}专业key:{}", bzksZy.getMc(), bzksZy.getDm() + yxInfo.getId());
                            WxDept zyDept = wxDeptMapper.selectDept(new WxDept(null, null, null, null, nj.getPx(), bzksZy.getDm(), "2"));
    //                        if (wxDeptHashMap.containsKey(bzksZy.getDm() + yxInfo.getId())) {
    //                            WxDept wxDept1 = wxDeptMapper.selectDept(new WxDept(null, null, null, yxInfo.getId(), null, bzksZy.getDm(), null));
                            if (zyDept != null) {
                                dept.setId(zyDept.getId());
                                if (!dept.equals(zyDept)) {
                                    wxApi.updateDept(dept);
                                }
                            } else {
                                if (wxApi.creatDept(dept)) {
                                    log.info("{}:添加专业部门：{}成功", Thread.currentThread().getName(), bzksZy.getMc());
                                } else {
                                    log.error("{}:添加专业失败", bzksZy.getMc());
                                }
                            }

                            //班级数据
                            List<BzksBj> bzksBjList = bzksBjMapper.selectList(new QueryWrapper<BzksBj>().eq("yxdm", yx.getDm()).eq("zydm", bzksZy.getDm()).eq("nj", year));
                            WxDept zyInfo = wxDeptMapper.selectDept(new WxDept(null, bzksZy.getMc(), null, yxInfo.getId(), null, null, null));
                            tempDepts.put(zyInfo.getId(), zyInfo);
                            for (BzksBj item : bzksBjList) {
                                WxDept bj = new WxDept(null, item.getBjmc(), null, zyInfo.getId(), zyInfo.getPx(), item.getBh(), "3");
                                WxDept bjDept = wxDeptMapper.selectDept(new WxDept(null, null, null, null, nj.getPx(), item.getBh(), "3"));
    //                            if (wxDeptHashMap.containsKey(item.getBh() + zyInfo.getId())) {
    //                                WxDept wxDept1 = wxDeptMapper.selectDept(new WxDept(null, null, null, zyInfo.getId(), null, item.getBh(), null));
                                if (bjDept != null) {
                                    bj.setId(bjDept.getId());
                                    if (!bj.equals(bjDept)) {
                                        wxApi.updateDept(bj);
                                    }
                                } else {
                                    if (wxApi.creatDept(bj)) {
                                        log.info("{}:添加班级部门：{}成功", Thread.currentThread().getName(), item.getBjmc());
                                    } else {
                                        log.error("{}:添加班级失败", item.getBjmc());
                                    }
                                }
                                WxDept bjInfo = wxDeptMapper.selectDept(new WxDept(null, item.getBjmc(), null, zyInfo.getId(), null, item.getBh(), null));
                                if (bjInfo != null) {
                                    tempDepts.put(bjInfo.getId(), bjInfo);
                                }
                                //人员数据

                            }
                        }
                    }
                }
                log.info("删除数据开始！");
                List<WxDept> wxDeptList = wxDeptMapper.selectAll();
                int delCount = 0;
                for (WxDept item : wxDeptList) {
                    if (!tempDepts.containsKey(item.getId())) {
                        //删除操作
                        if (wxApi.delDepts(item.getId())) {
                            delCount++;
                        }
                    }
                }
                log.info("删除数据{}+条", delCount);
            }, "同步线程").start();
        }finally {
            wxLock.unlock();
            return Result.success("success");
        }

    }

    @Override
    public Result updateWxDept(WxDept wxDept) {
//        log.info("开始更新!");
//        List<WxDept> wxDeptList = wxDeptMapper.selectList(new QueryWrapper<WxDept>());
//        for (Integer year : dept.allMap.keySet()) {
//            for (BzksYx yx : dept.allMap.get(year)) {
//                WxDept nj = wxDeptMapper.selectOne(new QueryWrapper<WxDept>().eq("name", year + "级"));
//                WxDept newyx = new WxDept(null, yx.getMc(), null, nj.getId(), nj.getPx(), yx.getDm(), "1");
//                WxDept wxDept1 = wxDeptMapper.selectOne(new QueryWrapper<WxDept>().eq("type_id",yx.getDm()).eq("type","1").eq("parentid",nj.getId()));
//                if (!wxDept1.equals("")){
//                    if (!newyx.equals(wxDept1)){
//                        if (wxApi.updateDept(wxDept)) {
//                            log.info("更新部门 {}成功!", wxDept.getId());
//                        } else {
//                            log.error("部门 {}更新失败", wxDept.getId());
//                        }
//                    }
//                }else {
//                    wxApi.creatDept(newyx);
//                }
//
//
//
//            }
//        }
//
////
//        for (WxDept item : wxDeptList) {
//            if (item.getType().equals("1")) {//院系表
//                BzksYx yx = bzksYxMapper.selectOne(new QueryWrapper<BzksYx>().eq("dm", item.getType_id()));
//                if (yx == null) {
//                    wxApi.deleteDept(item.getId());//有问题暂时保留
//                } else {
////                    List<WxDept> wxDepts = wxDeptMapper.selectList(new QueryWrapper<WxDept>().eq("type_id",yx.getDm()));
//                    WxDept wxDept1 = new WxDept(item.getId(),yx.getMc(),null,item.getParentid(),item.getPx(),yx.getDm(),item.getType());
//                    if (!item.equals(wxDept1)){
//                        if (wxApi.updateDept(wxDept)) {
//                            log.info("更新部门 {}成功!", wxDept.getId());
//                        } else {
//                            log.error("部门 {}更新失败", wxDept.getId());
//                        }
//                    }
//
//                }
//
//
//            } else if (item.getType_id().equals("2")) {//专业表
//
//            } else if (item.getType_id().equals("3")) {//班级表
//
//            }
//        }
//
//
        if (wxApi.updateDept(wxDept)) {
            log.info("更新部门 {}成功!", wxDept.getId());
        } else {
            log.error("部门 {}更新失败", wxDept.getId());
        }
        return Result.success("update WxDept success!");
    }

    @Override
    public Result delWxDept(int deptId) {
        if (wxApi.deleteDept(deptId)) {
            log.info("删除部门 {}成功!", deptId);
            return Result.success("del WxDept ok!");
        } else {
            log.error("部门 {}删除失败", deptId);
            return Result.error("del WxDept fail!");
        }

    }
}
